<template>
  <div class="test">
    <div v-show="isQuestionnaire">
      <h2>问卷</h2>
      <button @click="sendQuestionnaire">提交问卷</button>
    </div>
  </div>
</template>

<script setup>
  import { onBeforeUnmount, onUnmounted, reactive, ref } from 'vue'
  import { Questionnaire as QuestionnaireSDK } from '@polyv/interactions-receive-sdk';

  const isQuestionnaire = ref(false); // 是否显示问卷
  const $data = reactive({
    questionnaireSDK: null,// 问卷SDK实例
    questionId: '',
  })

  const sendQuestionnaire = async () => {
    const res = await $data.questionnaireSDK.answerQuestion([{"questionId": $data.questionId, "answer": "A"}])
    console.log('sendQuestionnaire', res)
  }

  $data.questionnaireSDK = new QuestionnaireSDK();
  console.log($data.questionnaireSDK)

  $data.questionnaireSDK.on($data.questionnaireSDK.events.START_QUESTIONNAIRE, function(msg) {
    console.log('收到问卷消息', msg);
    $data.questionId = msg.questions[0].questionId;
    isQuestionnaire.value = true
  });
  $data.questionnaireSDK.on($data.questionnaireSDK.events.STOP_QUESTIONNAIRE, function(msg) {
    console.log('收到问卷结束消息', msg);
    isQuestionnaire.value = false
  });
  onBeforeUnmount(() => {
    if($data.questionnaireSDK){
      $data.questionnaireSDK.destroy();
    }
  })
</script>
<style scoped>
  .test {
    position: fixed;
    right: 20px;
    top: 20px;
  }
  .test h2 {
    color: red;
  }
</style>

